package com.app.h5;


import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.app.h5.bean.DomainBean;
import com.app.h5.bean.H5Bean;
import com.app.h5.databinding.ActivitySplashBinding;
import com.app.h5.util.CommonDialog;
import com.app.h5.util.GsonUtil;
import com.app.h5.util.NetworkInterceptor;
import com.app.h5.util.SPUtil;
import com.gyf.immersionbar.ImmersionBar;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;

public class SplashActivity extends AppCompatActivity {
    public static final String TAG = "SplashActivity";
    public static final String H5_URLS = "h5_urls";
    public static final String URL1 = "https://inl.appsusa.net/site/api/c/site/getAppDomainsLandingList";
    public static final String URL2 = "/site/api/c/site/getExtensionUrl?domain=";//"https://hk001app.huosx.com/site/api/c/site/getExtensionUrl?domain=hk001app.huosx.com";
    private ActivitySplashBinding binding;
    private OkHttpClient okHttpClient;
    private boolean resultOk = false;
    private int failCount = 0;
    private List<Call> calls = new ArrayList<>();
    private CommonDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySplashBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
        initOk();
        requestDomain();
    }

    /**
     * 外层请求,第一次失败会发起第二次
     */
    private void requestDomain() {
        Request request = new Request.Builder().url(URL1).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                ResponseBody body = response.body();
                if (response.code() == 200 && body != null) {
                    try {
                        String content = body.string();
                        if (!TextUtils.isEmpty(content)) {
                            DomainBean domainBean = GsonUtil.fromJsonObj(content, DomainBean.class);
                            if (domainBean != null && domainBean.data != null && domainBean.data.allWebList != null && !domainBean.data.allWebList.isEmpty()) {
                                List<String> list = new ArrayList<>();
                                for (DomainBean.DataBean.AllWebListBean datum : domainBean.data.allWebList) {
                                    if (datum != null && datum.domain != null && !datum.domain.isEmpty() && !TextUtils.isEmpty(datum.domain.get(0))) {
                                        String trimUrl = datum.domain.get(0).trim();
                                        if (trimUrl.startsWith("http")) {
                                            list.add(trimUrl);
                                        } else {
                                            Log.d("OK_LOG_INIT", "error domain url " + datum);
                                        }
                                    } else {
                                        Log.d("OK_LOG_INIT", "invalid domain url " + datum);
                                    }
                                }
                                if (!list.isEmpty()) {
                                    requestH5(list);
                                } else {
                                    runOnUiThread(SplashActivity.this::showError);
                                }
                            } else {
                                runOnUiThread(SplashActivity.this::showError);
                            }
                        } else {
                            runOnUiThread(SplashActivity.this::showError);
                        }
                    } catch (Exception e) {
                        runOnUiThread(SplashActivity.this::showError);
                    }
                } else {
                    runOnUiThread(SplashActivity.this::showError);
                }
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(SplashActivity.this::showError);
            }
        });
    }

    /**
     * 外层请求成功,内层最简单校验,失败了直接报错
     *
     * @param urlList
     */
    private void requestH5(List<String> urlList) {
        failCount = 0;
        resultOk = false;
        for (String urlDomain : urlList) {
            Request request = new Request.Builder().url(urlDomain + URL2 + getParams(urlDomain)).build();
            Call call = okHttpClient.newCall(request);
            calls.add(call);
            call.enqueue(new Callback() {

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    ResponseBody body = response.body();
                    if (response.code() == 200 && body != null) {
                        try {
                            String content = body.string();
                            if (!TextUtils.isEmpty(content)) {
                                H5Bean h5Bean = GsonUtil.fromJsonObj(content, H5Bean.class);
                                if (h5Bean != null && h5Bean.data != null && !h5Bean.data.isEmpty()) {
                                    List<String> list = new ArrayList<>();
                                    for (String datum : h5Bean.data) {
                                        if (datum != null && !TextUtils.isEmpty(datum.trim())) {
                                            String trimUrl = datum.trim();
                                            if (trimUrl.startsWith("http")) {
                                                list.add(trimUrl);
                                            } else {
                                                Log.d("OK_LOG_INIT", "error h5 url " + datum);
                                            }
                                        } else {
                                            Log.d("OK_LOG_INIT", "invalid h5 url " + datum);
                                        }
                                    }
                                    if (!list.isEmpty()) {
                                        if (!resultOk) {
                                            // list.add(list.get(0));
                                            resultOk = true;
                                            SPUtil.put(H5_URLS, list);
                                            runOnUiThread(() -> toMain());
                                        }
                                    } else {
                                        addErrorCount(urlList);
                                    }
                                } else {
                                    addErrorCount(urlList);
                                }
                            } else {
                                addErrorCount(urlList);
                            }
                        } catch (IOException e) {
                            addErrorCount(urlList);
                        }
                    } else {
                        addErrorCount(urlList);
                    }
                }

                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    addErrorCount(urlList);
                }
            });
        }
    }

    private String getParams(String urlNextDomain) {
        return urlNextDomain.replace("https://", "").replace("http://", "");
    }

    private void addErrorCount(List<String> urlList) {
        failCount++;
        if (!resultOk) {
            if (failCount == urlList.size()) {
                runOnUiThread(this::showError);
            }
        }
    }

    private synchronized void showError() {
        /*binding.progressbar.setVisibility(View.GONE);
        binding.tvDesc.setText("检测失败");
        binding.tvBtn.setVisibility(View.VISIBLE);
        binding.tvBtn.setOnClickListener(view -> {
            binding.progressbar.setVisibility(View.VISIBLE);
            binding.tvDesc.setText("线路检测中...");
            binding.tvBtn.setVisibility(View.GONE);
            requestOut(URL1);
        });*/
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            dialog.show();
            return;
        }
        dialog = new CommonDialog(this, false, new CommonDialog.OnCommitListener() {
            @Override
            public void close() {
                finish();
                System.exit(0);
            }

            @Override
            public void confirm() {
                finish();
                System.exit(0);
            }
        });
        dialog.show();
    }

    @NonNull
    private Interceptor getLogInterceptor() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> Log.d("OK_LOG", "data = " + message));
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return loggingInterceptor;
    }

    private void initOk() {
        OkHttpClient.Builder builder = new OkHttpClient
                .Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new NetworkInterceptor());
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(getLogInterceptor());
        }
        okHttpClient = builder.build();
    }

    private void toMain() {
        for (Call call : calls) {
            if (call != null) {
                call.cancel();
            }
        }
        WebViewActivity.toWebViewActivity(this);
        finish();
    }

    private void init() {
        ImmersionBar.with(this)
                .statusBarColor(com.luck.picture.lib.R.color./*statusBarColor*/ps_color_transparent)
                .statusBarDarkFont(true)
                .fitsSystemWindows(false)
                //.navigationBarColor(R.color.transparent)
                //.navigationBarDarkIcon(isDarkTheme())
                .init();
    }

    /*@Override
    protected void onDestroy() {
        super.onDestroy();
        for (Call call : calls) {
            if (call != null) {
                call.cancel();
            }
        }
    }*/
}
